package cn.dazhou.wificonnectdemo.wifi

import android.annotation.SuppressLint
import android.content.Context
import android.net.ConnectivityManager
import android.net.wifi.WifiConfiguration
import android.net.wifi.WifiManager
import cn.dazhou.wificonnectdemo.App
import cn.dazhou.wificonnectdemo.Timber

/** wifi工具 */
@Suppress("DEPRECATION")
object WifiUtil {

    val wifiManager by lazy { App.app.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager }
    val connectivityManager by lazy { App.app.applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager }

    /** 判断wifi是否连接 */
    @SuppressLint("MissingPermission")
    fun isWifiConnected(): Boolean {
        @Suppress("DEPRECATION") val networkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
        return networkInfo?.let { networkInfo.isConnected } ?: false
    }

    /** 获取连接的wifi名称，实际测试发现wifi未连接时返回<unknown ssid>，所以先判断一下是否连接再获取名字 */
    fun getWifiName(): String? = if (isWifiConnected()) wifiManager.connectionInfo?.ssid?.replace("\"","") else "wifi未连接"

    /** 连接指定的wifi */
    @SuppressLint("MissingPermission")
    fun connectToWiFi(wifiName: String, wifiPwd: String) {
        Timber.fi("准备连接wifi, wifiName = $wifiName, password = $wifiPwd")
        val configuredNetworks = wifiManager.configuredNetworks
        configuredNetworks?.forEach {
            Timber.fi("已配置的wifi：${it.SSID} - ${it.networkId}")
            val removeNetwork = wifiManager.removeNetwork(it.networkId) // 有时候发现无法移除
            if (removeNetwork) {
                wifiManager.saveConfiguration()
            }
            Timber.fi("移除已配置的wifi：${it.SSID} - ${it.networkId}，结果：$removeNetwork")
        }

        val wifiConfig = WifiConfiguration()
        wifiConfig.SSID = "\"$wifiName\""
        wifiConfig.preSharedKey ="\"$wifiPwd\""

        val networkId = wifiManager.addNetwork(wifiConfig) // 有时候发现返回了-1，特别是在上面调用removeNetwork失败的时候，这里的addNetwork肯定也失败。
        if (networkId != -1) {
            val disconnect = wifiManager.disconnect()
            val enableNetwork = wifiManager.enableNetwork(networkId, true)
            val reconnect = wifiManager.reconnect()
            // 注：即使这个wifi从来没有连接过，且这个wifi的设备也没开机，这里的各种api调用也会返回true的。等wifi设备开机时，它会自动去连接这个wifi
            Timber.fi("已调用连接wifi(${wifiName})函数, networkId = $networkId, disconnect = $disconnect, enableNetwork = $enableNetwork, reconnect = $reconnect")
        } else {
            Timber.fi("连接wifi(${wifiName})失败, networkId = $networkId")
        }
    }

}